//
//  PaperErrorsViewModel.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/18.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import RxSwift
import RxDataSources
import RxCocoa

class PaperErrorsViewModel: LSFRefreshProtocol {
    var disposeBag = DisposeBag()
    
    var vmDatas = Variable([PaperErrorsSection]())
    var refreshStatus = Variable<LSFRefreshStatus>(.none)
    
    ///是否是空数据
    var isNull = Variable<Bool>(false)
    
    var requestCommand = PublishSubject<Bool>()
    init() {
        self.requestCommand.subscribe(onNext: { [weak self] (isPull) in
            self?.getErrors()
        }).disposed(by: disposeBag)
    }
    
    func getErrors() {
        paperProvider.rx
            .request(.errorList)
            .asObservable()
            .mapRespnseToObjectArray(type: PaperErrorsModel.self)
            .subscribe(onNext: { [weak self] (models) in
            
            guard let strongSelf = self else { return }
            let section = PaperErrorsSection.init(items: models)
            strongSelf.vmDatas.value = [section]
        }, onError: { [weak self] (error) in
            self?.refreshStatus.value = .endHeaderRefresh
        }, onCompleted: { [weak self] in
            stopAnimating()
            self?.isNull.value = (self?.vmDatas.value.first?.items.count == 0)
            self?.refreshStatus.value = .endHeaderRefresh
        }).disposed(by: disposeBag)
    }
}

struct PaperErrorsSection {
    var items: [PaperErrorsModel]
}

extension PaperErrorsSection: SectionModelType {
    typealias Item = PaperErrorsModel
    init(original: PaperErrorsSection, items: [PaperErrorsModel]) {
        self = original
        self.items = items
    }
}

